package 数组.移除元素_快慢指针.含退格的字符串;

import java.util.Stack;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/11 15:30
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String s = "y#fo##f";
        String t = "y#f#o##f";
        System.out.println(backspaceCompare2(s, t));
    }

    //栈
    public static boolean backspaceCompare(String s, String t) {
        System.out.println(getStr(s));
        System.out.println(getStr(t));
        if (getStr(s).equals(getStr(t))){
            return true;
        }
        return false;
    }
    public static String getStr(String str){
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '#' && stack.size() != 0){
                stack.pop();
            }else if (str.charAt(i) != '#'){
                stack.push(str.charAt(i));
            }
        }
        StringBuilder sb = new StringBuilder();

        while (stack.size() > 0){
            sb.append(stack.pop());
        }
        return String.valueOf(sb);
    }

    //双向指针
    public static boolean backspaceCompare2(String s, String t) {
        //System.out.println(getStr2(s));
        System.out.println(getStr2(t));
        if (getStr2(s).equals(getStr2(t))){
            return true;
        }
        return false;
    }
    public static String getStr2(String str){
        int slowIndex = 0;
        char[] chars = str.toCharArray();
        for (int fastIndex = 0; fastIndex < chars.length; fastIndex++) {
            if (str.charAt(fastIndex) == '#' && slowIndex > 0){
                slowIndex--;
            }else if (str.charAt(fastIndex) != '#' ){
                chars[slowIndex] = chars[fastIndex];
                slowIndex++;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < slowIndex ; i++) {
            sb.append(chars[i]);
        }
        return String.valueOf(sb);
    }


}
